#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
环境检查插件
"""

import sys
import platform
import subprocess
from pathlib import Path

# 导入统一的环境配置
from env_setup import setup_environment, ENV_CONFIG

# 使用统一的环境配置
ENV_CONFIG = setup_environment()

class EnvironmentChecker:
    """环境检查插件类"""
    
    def __init__(self):
        self.project_root = ENV_CONFIG['PROJECT_ROOT']
        
    def start(self) -> bool:
        """插件启动方法"""
        print("🔍 环境检查工具")
        print("=" * 40)
        
        while True:
            print("\n请选择检查项目:")
            print("1. 🐍 Python环境")
            print("2. 📦 依赖包")
            print("3. 📁 目录结构")
            print("4. 🔧 系统信息")
            print("5. ↩️ 返回主菜单")
            
            try:
                choice = input("\n请选择 (1-5): ").strip()
                
                if choice == "1":
                    self.check_python_environment()
                elif choice == "2":
                    self.check_dependencies()
                elif choice == "3":
                    self.check_directory_structure()
                elif choice == "4":
                    self.check_system_info()
                elif choice == "5":
                    return True
                else:
                    print("❌ 无效选项")
                    
            except KeyboardInterrupt:
                print("\n👋 返回主菜单")
                return True
            except Exception as e:
                print(f"❌ 错误: {e}")
                
        return True
    
    def check_python_environment(self):
        """检查Python环境"""
        print("\n🐍 Python环境检查:")
        print(f"  Python版本: {sys.version}")
        print(f"  平台: {platform.platform()}")
        print(f"  架构: {platform.architecture()}")
        print(f"  可执行文件: {sys.executable}")
        
        # 检查pip
        try:
            result = subprocess.run([sys.executable, "-m", "pip", "--version"], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print(f"  Pip版本: {result.stdout.strip()}")
            else:
                print("  ❌ Pip不可用")
        except Exception as e:
            print(f"  ❌ 检查Pip失败: {e}")
    
    def check_dependencies(self):
        """检查依赖包"""
        print("\n📦 依赖包检查:")
        
        requirements_file = self.project_root / "requirements.txt"
        if not requirements_file.exists():
            print("  ❌ requirements.txt 文件不存在")
            return
            
        try:
            with open(requirements_file, 'r', encoding='utf-8') as f:
                requirements = [line.strip() for line in f if line.strip() and not line.startswith('#')]
            
            print(f"  需要检查 {len(requirements)} 个依赖包:")
            
            for req in requirements:
                package_name = req.split('==')[0].split('>=')[0].split('<=')[0]
                try:
                    result = subprocess.run([
                        sys.executable, "-c", f"import {package_name}; print('OK')"
                    ], capture_output=True, text=True)
                    
                    if result.returncode == 0:
                        print(f"    ✅ {package_name}")
                    else:
                        print(f"    ❌ {package_name}")
                except Exception:
                    print(f"    ❌ {package_name}")
                    
        except Exception as e:
            print(f"  ❌ 检查依赖失败: {e}")
    
    def check_directory_structure(self):
        """检查目录结构"""
        print("\n📁 目录结构检查:")
        
        important_dirs = [
            "ComfyUI",
            "Scripts", 
            "models",
            "outputs"
        ]
        
        for dir_name in important_dirs:
            dir_path = self.project_root / dir_name
            if dir_path.exists():
                print(f"  ✅ {dir_name}/")
            else:
                print(f"  ❌ {dir_name}/ (不存在)")
    
    def check_system_info(self):
        """检查系统信息"""
        print("\n🔧 系统信息:")
        print(f"  操作系统: {platform.system()} {platform.release()}")
        print(f"  处理器: {platform.processor()}")
        print(f"  机器类型: {platform.machine()}")
        
        # 检查内存
        try:
            import psutil
            memory = psutil.virtual_memory()
            print(f"  内存: {memory.total // (1024**3)} GB 总计, {memory.available // (1024**3)} GB 可用")
        except ImportError:
            print("  内存: 无法检查 (需要安装psutil)")
        
        # 检查磁盘空间
        try:
            disk = psutil.disk_usage(str(self.project_root))
            print(f"  磁盘空间: {disk.free // (1024**3)} GB 可用")
        except:
            print("  磁盘空间: 无法检查") 